/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (head == NULL || head->next == NULL) {
            return head;
        }

        ListNode *head0 = NULL;
        ListNode *head1 = NULL;
        ListNode *tail0 = NULL;
        ListNode *tail1 = NULL;
        ListNode *cur = head;

        while (cur) {
            if (cur->val < x) {
                if (head0 == NULL) {
                    head0 = tail0 = cur;
                } else {
                    tail0->next = cur;
                    tail0 = cur;
                }
            } else {
                if (head1 == NULL) {
                    head1 = tail1 = cur;
                } else {
                    tail1->next = cur;
                    tail1 = cur;
                }
            }
            cur = cur->next;
        }
        if (head0 == NULL) {
            return head1;
        } else if (head1 == NULL) {
            return head0;
        } else {
            tail0->next = head1;
            tail1->next = NULL;
            return head0;
        }
    }
};
